package com.gxuwz.web.struts2;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.struts2.ServletActionContext;

import com.gxuwz.annotation.LogMsg;
import com.gxuwz.common.Const;
import com.gxuwz.entity.SysDepartment;
import com.gxuwz.entity.SysLaboratory;
import com.gxuwz.entity.SysRole;
import com.gxuwz.entity.SysUser;
import com.gxuwz.service.IDepartmentService;
import com.gxuwz.service.ILaboratoryService;
import com.gxuwz.service.IRoleService;
import com.gxuwz.service.IUserService;
import com.gxuwz.util.DateUtils;
import com.gxuwz.util.Page;
import com.gxuwz.web.AbstractBaseController;
import com.gxuwz.web.struts2.vo.Result;
import com.opensymphony.xwork2.util.CreateIfNull;
import com.opensymphony.xwork2.util.Element;
import com.opensymphony.xwork2.util.KeyProperty;

/**
 * 用户控制器
 * @author pan
 * @date 2017年5月28日
 */
public class UserController extends AbstractBaseController{
	
	private SysUser user;
	
	/**
	 * 配置页面传值映射
	 */
	@Element(com.gxuwz.entity.SysRole.class)
	@KeyProperty("id")
	@CreateIfNull(true)
	private Set<SysRole> roles = new HashSet<>();//jsp属性注入必须初始化
	
	@Element(com.gxuwz.entity.SysLaboratory.class)
	@KeyProperty("id")
	@CreateIfNull(true)
	Set<SysLaboratory> user_lab = new HashSet<>();
	
	private List<Integer> ids;	//	获取复选框的值
	private Integer departmentID;
	@Resource
	private IUserService userService;
	@Resource
	private IRoleService roleService;
	@Resource
	private IDepartmentService departmentService;
	@Resource
	private ILaboratoryService laboratoryService;
	/**
	 * 
	 */
	private static final long serialVersionUID = 784331025473234456L;
	

	public String addPrompt(){
		setPrompt("/index.jsp");
		return SUCCESS;
	}
	
	public String loginPrompt(){
		setPrompt("/login.jsp");
		return SUCCESS;
	}
	public String updatePrompt(){
		//查找要修改的用户信息
		SysUser u = userService.findByUserName(user.getUserName());
		//查找所有部门
		List<SysDepartment> departmentList = departmentService.getAllFromTable();
		//查找所有角色
		List<SysRole> list = roleService.getAllFromTable();
		//去掉用户已有的角色
		for (int i=0;i<list.size();i++) {
			if(u.getUser_role().contains(list.get(i))){
				list.remove(list.get(i));
				i--;
			}

		}
		request.put("departmentList", departmentList);
		
		String msg = (String) session.get("msg");
		session.remove("msg");
		if(msg!=null){
			request.put("msg", msg);
		}
		request.put("list", list);
		request.put("user", u);
		setPrompt("/WEB-INF/pages/user/user_updata.jsp");
		return SUCCESS;
	}

	@LogMsg(msg="用户登陆")
	public String doLogin(){
		setPrompt("/WEB-INF/pages/main.jsp");	
		return SUCCESS;
	}
	
	
	/**
	 * 退出登陆
	 * @return
	 */
	public String doLogout(){
		session.clear(); // 清除session
		session.put("msg", Const.LOGOUT_MSG);	// 重定向不能把信息放到request中
		setPrompt("User_loginPrompt.action");		
		return "reposition";
	}
	
	/**
	 *  分页
	 * @return
	 */
	public String listPrompt(){		
		Page<SysUser> page = new Page<SysUser>(); //创建分页对象指定泛型		
		page.setOnePageNum(10); //设置单页记录数 默认5		
		page.setPageNo(pageNo==null?1:pageNo); //设置当前页数 默认1
		page.setClazz("User");
		userService.findForPage(page);		
		request.put("page", page);		
		setPrompt("/WEB-INF/pages/user/user_list.jsp");
		return SUCCESS;
	}
	
	/**
	 * 跳转到添加用户页面
	 * @return String
	 */
	public String toAdd(){
		List<SysDepartment> departmentList = departmentService.getAllFromTable();
		List<SysRole> list = roleService.getAllFromTable();
		request.put("departmentList", departmentList);
		request.put("list", list);
		String msg = (String) session.get("msg");
		session.remove("msg");
		if(msg!=null){
			request.put("msg", msg);
		}
		setPrompt("/WEB-INF/pages/user/user_add.jsp");
		return SUCCESS;
	}
	
	/**
	 * 添加用户
	 * 
	 * @return
	 */
	@LogMsg(msg="新增登陆")
	public String addUser(){
		System.out.println(user_lab.size());
		user.setUser_role(roles);
		user.setUser_lab(user_lab);
		user.setCreateDate(DateUtils.getCurrentDate());
		userService.save(user);
		session.put("msg", "添加成功！");
		setPrompt("User_toAdd.action");
		return "reposition";
	}
	
	/**
	 * 检查用户名是否存在
	 * @return
	 * @throws IOException 
	 */
	public void checkName(){
		
		Result result = new Result();
		result.setCode(1);
		SysUser u = userService.findByUserName(user.getUserName());
		if(u!=null){
			result.setCode(0);
			result.setMsg("名字已存在！");
		}
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.print(gson.toJson(result));
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(writer!=null){
		        writer.close();
			}
		}

	}
	
	/**
	 * 按部门查找实验室（AJAX 返回JSON）
	 */
	public void findLaboratoryByDepartmentID(){
		PrintWriter writer = null;
		Result result = new Result();
		try{
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("UTF-8");
			writer = response.getWriter();
			List<SysLaboratory> laboratoryList =  laboratoryService.findLabByDeptId(departmentID);
			result.setData(laboratoryList);
			result.setCode(1);
		}catch(Exception e){
			e.printStackTrace();
			result.setCode(0);
			result.setMsg("部门编号不正确");
			throw new RuntimeException("部门编号不正确，应该为数字");
		}finally{
			if(writer!=null){
				JsonConfig jsonConfig = new JsonConfig();
			    jsonConfig.setIgnoreDefaultExcludes(false);
			    //防止自包含
			    jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

			    //这里是核心，过滤掉不想使用的属性(因为这里是取指定部门的实验室，所以不需要再去找部门列表)
			    jsonConfig.setExcludes(new String[]{"department"});
			     
			    JSONObject jsonObj = JSONObject.fromObject(result, jsonConfig);
				
				writer.print(jsonObj.toString());
							
				writer.flush();
		        writer.close();
			}
		}
		
	}
	
	@LogMsg(msg="更新用户")
	public String doUpdate(){
		user.setUser_lab(user_lab);
		user.setUser_role(roles);
		userService.updateById(user);
		session.put("msg", "更新成功！");
		setPrompt("User_updatePrompt.action?user.userName="+user.getUserName());
		return "reposition";
	}
	
	@LogMsg(msg="删除用户")
	public String doBatchDelete(){
		userService.batchDelete(ids);
		setPrompt("User_listPrompt.action");
		return "reposition";
	}
	
	
	public SysUser getUser() {
		return user;
	}

	public void setUser(SysUser user) {
		this.user = user;
	}

	public Set<SysRole> getRoles() {
		return roles;
	}

	public void setRoles(Set<SysRole> roles) {
		this.roles = roles;
	}

	public List<Integer> getIds() {
		return ids;
	}

	public void setIds(List<Integer> ids) {
		this.ids = ids;
	}

	public Integer getDepartmentID() {
		return departmentID;
	}

	public void setDepartmentID(Integer departmentID) {
		this.departmentID = departmentID;
	}

	public Set<SysLaboratory> getUser_lab() {
		return user_lab;
	}

	public void setUser_lab(Set<SysLaboratory> user_lab) {
		this.user_lab = user_lab;
	}
	
}
